package com.story.story_serve.controller;


import com.story.story_pojo.userinfo;
import com.story.story_serve.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * ClassName:  UserController
 * description:
 *
 * @ author:郭海龙
 * @ Create：2024/4/30 15:19
 * @ Version:1.0
 */
@CrossOrigin        // 跨域问题  实现前后端分离
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    // 查询userinfo实体的所有数据
    @RequestMapping("/getAllUsers")
    public List<userinfo> getAllUsers() {
        return userService.getAllUsers();
    }

    // 用户登录
    @RequestMapping("/login")
    public String login(userinfo userinfo, HttpSession session) {
        return userService.login(userinfo, session);
    }

    // 通过session获取当前登录的用户数据
    @RequestMapping("/getUser")
    public userinfo getUser(HttpSession session) {
        return (userinfo) session.getAttribute("user");
    }

    // 注销
    @RequestMapping("/loginOut")
    public RedirectView loginOut(HttpSession session) {
        //使session失效
        session.invalidate();
        return new RedirectView("/login.html");
    }

    // 根据id删除用户
    @RequestMapping("/delete")
    public int delete(userinfo user) {
        return userService.delete(user);
    }

    // 用户注册
    @PostMapping("/register")
    public String register(userinfo userinfo) {
        return userService.register(userinfo);
    }

    // 用户头像上传
    @PostMapping("/uploadImg")
    public String uploadImg(@RequestParam(name = "file") MultipartFile file) {
        // 判断是否有数据
        if (file.isEmpty()) {
            return "图片不存在";
        }
        //设置图片名称，重命名(a:1.png b:1.png)
        String originalFilename = file.getOriginalFilename();
        //获取后缀名
        String ext = "." + originalFilename.split("\\.")[1];//1.png
        Long time = new Date().getTime();
        //新的文件名
        String newFilename = time + ext;
        //上传图片
        String localPath = "D:\\Program Files\\java\\javacode\\story\\story_serve\\src\\main\\resources\\static\\userimg\\";
        String path = localPath + newFilename;
        try {
            file.transferTo(new File(path));//返回图片地址
            return "http://localhost:8080/userimg/" + newFilename;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "图片上传失败";
    }

    // 修改个人数据
    @RequestMapping("/updateMyInfo")
    public String updateMyInfo(userinfo userinfo, HttpSession session){
        return userService.updateMyInfo(userinfo,session);
    }
}
